import {BaseCrudApi} from "~/api/util/BaseService";
import {Org} from "~/api/system/org/types";
import {reactive} from "vue";
import {CreateState} from "~/api/types";
import {UnwrapNestedRefs} from "@vue/reactivity";

export class OrgApi extends BaseCrudApi<Org> {

    baseUrl: string = "/system/org";

    treeState = reactive({
        data: [],
        tree: [],
    });

    constructor(renderTree: boolean) {
        super();
        if (renderTree) {
            this.getTree();
        }
    }

    getTree() {
        this.get("/tree").then(res => {
            if (res.ok) {
                this.treeState.tree = [];
                this.treeState.data = res.data as any;
                // @ts-ignore
                this.treeState.tree.push({id: undefined, name: "全部", pid: undefined});
                // @ts-ignore
                (res.data).forEach((item: any) => {
                    // @ts-ignore
                    this.treeState.tree.push(item);
                });
            }
        });
    }

    onTreeClick(e: any) {
        this.filterTable({pid: e.id});
    }

    beforeCreate(createState: UnwrapNestedRefs<CreateState<Org>>) {
        super.beforeCreate(createState);
        createState.form.sort = 0;
    }

    afterSubmit() {
        super.afterSubmit();
        this.getTree();
    }

    afterDelete() {
        super.afterDelete();
        this.getTree();
    }
}
